package com.song.Utils;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;

@Slf4j(topic = "c.ShutdownHook")
public class ShutdownHook {
    //使用线程池处理关闭操作
    private final ExecutorService threadPool = ThreadPoolFactory.createDefaultThreadPool("shutdown-hook");//创建名称为 "shutdown-hook"的线程池处理
    private static final ShutdownHook shutdownhook = new ShutdownHook();

    public static ShutdownHook getShutdownhook() {
        return shutdownhook;
    }

    public void addClearAllHook() {
        log.info("关闭后将自动注销所有服务。。。");

        /**
         * Runtime 对象是 JVM 虚拟机的运行时环境，调用其 addShutdownHook 方法增加一个钩子函数，
         * 创建一个新线程调用 clearRegistry 方法完成注销工作。这个钩子函数会在 JVM 关闭之前被调用。
         */
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            NacosUtil.clearRegistry();
            threadPool.shutdown();
        }));
    }
}
